<template>
  <div ref="imageWrapper">
    <a-card style="margin-bottom: 15px">
      <div class="table-page-search-wrapper">
        <a-form-model ref="ruleForm" :model="queryParam" :rules="rules" layout="inline" @keyup.enter.native="loadData">
          <a-row :gutter="24">
            <a-col :md="5" :sm="8">
              <a-form-model-item label="账套/核算单元" prop="accName">
                <a-input
                  @click.native="openOrganModel"
                  v-model="queryParam.accName"
                  readOnly
                  placeholder="请选择账套/核算单元"
                />
              </a-form-model-item>
            </a-col>
            <!-- <a-col :md="6" :sm="8">
              <a-form-model-item label="单位" prop="unitCode">
                <j-select-unit-info
                  v-model="queryParam.unitCode"
                  :trigger-change="true"
                  customReturnField="id"
                  :multi="false"
                ></j-select-unit-info>
              </a-form-model-item>
            </a-col> -->
            <a-col :md="4" :sm="8">
              <a-form-model-item label="月份" prop="month">
                <a-range-picker
                  format="yyyy-MM"
                  value-format="yyyy-MM"
                  v-model="queryParam.month"
                  @change="handleDatechange"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="8">
              <a-form-model-item label="科目选择" prop="subjectCode">
                <a-tree-select
                  v-model="queryParam.subjectCode"
                  tree-data-simple-mode
                  style="width: 220px"
                  show-search
                  treeNodeFilterProp="title"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择科目"
                  :tree-data="subjectTreeData"
                  allow-clear
                />
                <!-- <a-select allowClear placeholder="请选择科目" v-model="queryParam.subjects">
                  <a-select-option :value="item.value" v-for="item in subjectsList" :key="item.id">{{
                    item.label
                  }}</a-select-option>
                </a-select> -->
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="8">
              <a-form-model-item label="科目展示" prop="codeType">
                <j-dict-select-tag
                  :default-value="1"
                  v-model="queryParam.codeType"
                  placeholder="请选择"
                  dictCode="kmzs_codetype"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="4" :sm="8">
              <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" @click="loadData" icon="search">查询</a-button>
                <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">清除条件</a-button>
                <a-button
                  type="danger"
                  :loading="ydLoading"
                  @click="
                    () => {
                      if (this.tableData.length) {
                        const { accName = '', startMonth = '', endMonth = '', subjectCode = '' } = this.queryParam
                        let ydnr = `【科目编号：${subjectCode}】`
                        let time = `【${startMonth}～${endMonth}】【科目结构分析】`
                        this.addYd(queryParam, ydnr, time)
                      } else {
                        this.$message.error('空数据不能新建疑点')
                      }
                    }
                  "
                  icon="arrow-right"
                  style="margin-left: 8px"
                  >转疑点</a-button
                >
              </span>
            </a-col>
            <a-col v-if="isBackButton" :offset="20" :md="4" :sm="8" style="text-align: right">
              <a-button type="primary" style="margin-left: 8px" @click="backUppage"> 返回 </a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-row :gutter="12">
      <a-col :md="6">
        <!--  -->
        <a-card style="height: 675px">
          <div class="card_title">科目列表</div>
          <a-row :gutter="2" style="margin-bottom: 10px; padding: 0 10px">
            <a-col :md="20" style="display: flex">
              <span style="width: 30%; align-self: center">关键字：</span>
              <a-input placeholder="请输入科目编号或名称过滤" @input="handleListFilter"></a-input>
            </a-col>
          </a-row>
          <a-table
            :loading="loading"
            :customRow="Rowclick"
            :columns="columns"
            class="pointer_table"
            :data-source="tableData"
            :pagination="false"
            :scroll="{ x: 200, y: 510 }"
          ></a-table>
        </a-card>
      </a-col>
      <a-col :md="18">
        <a-card v-if="tableData.length > 0">
          <div class="card_title">图形显示</div>
          <div style="height: 598px; display: flex">
            <!-- style="width: 85%" -->
            <echarts style="width: 35%" :chartOpt="chartOpt" :istrigger="istrigger" />
            <div class="chart_table_box">
              <a-table
                :columns="chartColumns"
                bordered
                :pagination="false"
                :scroll="{ x: 200, y: 510 }"
                :data-source="chartTableData"
              >
                <span slot="icon" slot-scope="text, record, index">
                  <div class="icon" :style="{ backgroundColor: colors[index % 5] }"></div>
                </span>
              </a-table>
            </div>
            <!-- <div class="line_control">
              <div class="controls_item" v-for="item in chartLenged" :key="item.id">
                <icon-font :type="item.type"></icon-font>
                <a-checkbox>{{ item.label }}</a-checkbox>
              </div>
            </div> -->
          </div>
        </a-card>
      </a-col>
    </a-row>
    <YDModel ref="YDModel" :routerData="$route.path" />
    <CheckOrganModal ref="departModal" @ok="updateQueryParam"></CheckOrganModal>
  </div>
</template>

<script>
import echarts from '../components/echarts.vue'
import { Icon } from 'ant-design-vue'
import iconFont from '@/assets/font/iconfont'
import JSelectUnitInfo from '../JSelectUnitInfo'
import CheckOrganModal from '@/views/sj/sjxmzygl/yzzx/testcomponent/CheckOrganModal'
import { base64toImg } from '@/mixins/base64toImg'
import YDModel from '@/views/sj/components/YDModel'
import { YzzxListMixin } from '../../yzzx/mixins/YzzxListMixin.js'
import { beforeyearYM, currentYM } from '@/mixins/commontime.js'
import jumpConfigMixin from '@/views/sj/sjxmzygl/sjxmss/jumpConfigMixin'
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFont,
})

import pieChartOpt from './pieChartOpt'
import { getAction } from '@/api/manage'
import lineChartOpt from '../kmqsfx/lineChartOPt'
import { toMoney } from '../utils'

export default {
  name: 'kmqsfx',
  components: {
    echarts,
    IconFont,
    JSelectUnitInfo,
    CheckOrganModal,
    YDModel,
  },
  mixins: [base64toImg, YzzxListMixin, jumpConfigMixin],
  watch: {
    $route: {
      handler: function (to) {
        if (Object.keys(to.query).length) {
          this.disableMixinCreated = true
          this.queryParam = Object.assign(this.queryParam, to.query)
          this.queryParam.month = to.query.month.split(',')
          this.$nextTick(() => {
            this.loadData()
          })
        } else if (Object.keys(to.params).length && to.params.from == 'sjxmss') {
          let { accName, accId } = to.params
          this.queryParam.accName = accName
          this.queryParam.accCode = accId
          this.queryParam.subjectCode = '1001'
          this.isBackButton = true
          let { endDate, startDate } = JSON.parse(to.params.returnRecord)
          this.queryParam.startMonth = startDate && `${startDate.split('-')[0]}-${startDate.split('-')[1]}`
          this.queryParam.endMonth = endDate && `${endDate.split('-')[0]}-${endDate.split('-')[1]}`
          this.queryParam.month = [this.queryParam.startMonth, this.queryParam.endMonth]

          this.returnRecord = to.params.returnRecord
          this.$nextTick(() => {
            this.loadData()
          })
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      queryParam: {
        // unitCode: '',
        month: [beforeyearYM(2, 'years'), currentYM()],
        subjectCode: undefined,
        accName: '',
        accCode: '',
        codeType: 2,
      },
      isBackButton: false,
      tempDataSource: [],
      panelShow: false,
      chartShow: false,
      unitName: '',
      companyList: [],
      subjectsList: [],
      subjectTreeData: [],
      loading: false,
      month: [],
      chartColumns: [
        {
          title: '',
          dataIndex: 'index',
          key: 'index',
          width: '50px',
          scopedSlots: { customRender: 'icon' },
        },
        {
          title: '编号',
          dataIndex: 'subjectCode',
          key: 'subjectCode',
        },
        {
          title: '名称',
          dataIndex: 'subjectName',
          key: 'subjectName',
        },
        {
          title: '贷方',
          dataIndex: 'crediCurrency',
          key: 'crediCurrency',
          customRender: (text, record, index) => {
            if (Number(record.crediCurrency) != 0) return `${toMoney(Number(record.crediCurrency) / 10000)}  万元`
            else return `0万元`
          },
        },
        {
          title: '借方',
          dataIndex: 'debitCurrency',
          key: 'debitCurrency',
          customRender: (text, record, index) => {
            if (Number(record.debitCurrency) != 0) return `${toMoney(Number(record.debitCurrency) / 10000)}  万元`
            else return `0万元`
          },
        },
      ],
      colors: ['#01458e', '#9ed7ea', '#6c5dd2', '#4d98eb', '#bcd3ff'],
      chartLenged: [
        {
          id: 1,
          type: 'icon-qizhi-',
          label: '显示标识',
        },
        {
          id: 2,
          type: 'icon-tubiaozhutu',
          label: '显示科目名称',
        },
        {
          id: 3,
          type: 'icon-bingtu',
          label: '显示比例',
        },
      ],
      chartTableData: [],
      chartOpt: {
        id: 'pieChartOpt',
        options: pieChartOpt(),
      },

      rules: {
        // unitCode: [{ required: true, message: '请选择单位', trigger: 'change' }],
        month: [{ required: true, message: '请选择月份', trigger: 'change' }],
        subjectCode: [{ required: true, message: '请选择科目', trigger: 'change' }],
        accName: [{ required: true, message: '请选择账套' }],
        codeType: [{ required: true, message: '请选择' }],
      },
      columns: [
        {
          title: '科目编号',
          dataIndex: 'subjectCode',
          key: 'subjectCode',
        },
        {
          title: '科目名称',
          dataIndex: 'subjectName',
          key: 'subjectName',
        },
      ],
      tableData: [],
      chartLenged: [
        {
          id: 1,
          type: 'icon-qizhi-',
          label: '显示标识',
        },
        {
          id: 2,
          type: 'icon-tuli',
          label: '显示例子',
        },
        {
          id: 3,
          type: 'icon-bingtu',
          label: '显示比例',
        },
      ],
      istrigger: false,
      url: {
        subjectTree: '/sjyzzx/sjZxzyAccountSubject/queryAllSubjectTree',
        objlist: '/sjkmfx/sjSubjectsAnalyse/queryFinanceSubjectList2',
        line: '/sjkmfx/sjSubjectsAnalyse/queryFinanceSubjectStructure',
      },
    }
  },
  created() {
    this.getSubjectTree()
  },
  mounted() {
    this.$refs.ruleForm.resetFields()
  },
  methods: {
    updateQueryParam(data) {
      console.log(data, 'daat')
      let str1 = ''
      let str2 = ''
      data.map((item) => {
        // TODO 账套～～～
        str1 += item.accCode + ','
        str2 += item.accName + ','
      })
      if (str1.length > 0) {
        str1 = str1.substr(0, str1.length - 1)
      }
      if (str2.length > 0) {
        str2 = str2.substr(0, str2.length - 1)
      }
      this.queryParam.accCode = str1
      this.queryParam.accName = str2
    },
    openOrganModel() {
      this.$refs.departModal.edit()
    },
    handleListFilter(e) {
      if (e.target.value != null && e.target.value != undefined && e.target.value != '') {
        this.tableData = this.tempDataSource.filter(
          (item) => item.subjectCode.includes(e.target.value) || item.subjectName.includes(e.target.value)
        )
      } else {
        this.tableData = this.tempDataSource
      }
      //  筛选时默认显示第一个
      if (this.tableData.length > 0) this.getLineData(this.tableData[0].subjectCode, this.tableData[0])
    },
    searchReset() {
      this.queryParam = this.$options.data().queryParam
      this.$refs.ruleForm.resetFields()
      this.panelShow = false
      this.chartShow = false
      this.tableData = []
    },
    Rowclick(record, index) {
      let _this = this
      return {
        on: {
          click: () => {
            _this.getLineData(record.subjectCode, record)
          },
        },
      }
    },
    handleDatechange(dates) {
      this.queryParam.startMonth = dates[0]
      this.queryParam.endMonth = dates[1]
    },
    // // 查询
    loadData() {
      var params = this.queryParam //查询条件
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // this.getObjList(params)
          this.getTable(params)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getTable(params) {
      this.loading = true
      getAction(this.url.objlist, params).then((res) => {
        if (res.success) {
          this.tableData = res.result
          this.tempDataSource = res.result
          this.panelShow = true
          if (this.tableData.length || this.tempDataSource.length) {
            this.getLineData(this.tableData[0].subjectCode, this.tableData[0])
          }
        } else {
          this.$message.error(res.message)
        }
        this.loading = false
      })
    },
    getLineData(subjectCode, name) {
      let params = {
        ...this.queryParam,
        subjectCode: subjectCode,
      }
      getAction(this.url.line, params).then((res) => {
        if (res.success === true && res.code === 200) {
          this.chartTableData = res.result
          let data = res.result.map((item) => {
            return {
              name: item.subjectName,
              value: item.totalMoney,
            }
          })
          this.chartOpt.options = pieChartOpt({ data: data })
          this.chartShow = true
          this.istrigger = !this.istrigger
        } else {
          this.$message.error(res.message)
        }
      })
    },
  },
}
</script>
<style scoped>
.ant-select-dropdown {
  width: 220px;
}
</style>
<style lang="less" scoped>
@import '~@assets/less/common.less';
@import './index.less';

.pointer_table {
  /deep/ .ant-table-row {
    cursor: pointer;
  }
}
</style>